package com.jvm.optimize;

import com.sun.org.apache.bcel.internal.generic.NEW;

import java.util.Arrays;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.concurrent.*;

// 三个查询采用多线程并行执行
public class Demo1 {


    /**
     * 获取商品基本信息
     *
     * @param goodsId
     * @return
     * @throws InterruptedException
     */
    public String goodsDetailModel(long goodsId) throws InterruptedException {
        // 模拟耗时，休眠200ms
        TimeUnit.MILLISECONDS.sleep(200);
        return "商品id：" + goodsId + "，商品基本信息...";
    }

    /**
     * 获取商品图片列表
     *
     * @param goodsId
     * @return
     * @throws InterruptedException
     */
    public List<String> goodsImgsModelList(long goodsId) throws InterruptedException {
        // 模拟耗时，休眠200ms
        TimeUnit.MILLISECONDS.sleep(200);
        return Arrays.asList("图1", "图2", "图3");
    }


    /**
     * 获取商品描述信息
     *
     * @param goodsId
     * @return
     * @throws InterruptedException
     */
    public String goodsExtModel(long goodsId) throws InterruptedException {
        // 模拟耗时，休眠200ms
        TimeUnit.MILLISECONDS.sleep(200);
        return "商品id：" + goodsId + "，商品描述信息...";
    }


    // 创建一个线程池
    ExecutorService executorService = Executors.newFixedThreadPool(10);


    /**
     * 获取商品详情
     *
     * @param goodsId 商品id
     * @return
     * @throws ExecutionException
     * @throws InterruptedException
     */
    public Map<String, Object> goodsDetail(long goodsId) throws ExecutionException, InterruptedException {
        Map<String, Object> result = new HashMap<>();

        // 异步获取商品基本信息
        Future<String> goodsDetailModelFuture = executorService.submit(() -> goodsDetailModel(goodsId));
        // 异步获取商品图片列表
        Future<List<String>> goodsImgsModelListFuture = executorService.submit(() -> goodsImgsModelList(goodsId));
        // 异步获取商品描述信息
        Future<String> goodsExtModelFuture = executorService.submit(() -> goodsExtModel(goodsId));

        result.put("goodsDetailModel", goodsDetailModelFuture.get());
        result.put("goodsImgsModel", goodsImgsModelListFuture.get());
        result.put("goodsExtModel", goodsExtModelFuture.get());

        return result;
    }


    public static void main(String[] args) throws ExecutionException, InterruptedException {
        long startTime = System.currentTimeMillis();

        Map<String, Object> map = new Demo1().goodsDetail(1L);
        System.out.println(map);
        System.out.println("耗时（ms）：" + (System.currentTimeMillis() - startTime));

        /**
         *
         * 可以看出耗时 200 毫秒左右，性能提升了 2 倍，
         * 假如这个接口中还存在其他无依赖的操作，性能提升将更加显著，
         * 上面使用了线程池并行去执行 3 次查询的任务，
         * 最后通过 Future 获取异步执行结果。
         *
         */
    }


}
